<?php
		/**
		 * @desc 从excel导入数据到数据库中
		 */

		//公共部分
		include_once('./admin_global.php');
		
		$userInfo = $base->auth();
		$cssArr = array('common.css', 'upload_data.css');
		$jsArr  = array('upload_data.js');

		if ($_POST) {

			$upload_dir = APP_PATH . "uploads/";
			$errUrl = "errorpage.php?msg=";
			if (!is_dir($upload_dir)) {
				@mkdir($upload_dir, 0777) or 
					header("Location: ".SITE_URL.$errUrl."uploads文件创建失败");
			}
			$fileFieldName  = 'infoFile';

			$php_errors = array(1 => '文件过大，请重新上传',
								2 => '文件过大，请重新上传',
								3 => '文件不能完整上传',
								4 => '没有文件被选中'
								);
			//允许上传的文件后缀名
			$fileExt = array("xls", "xlsx");

			//确定文件是否上传成功
			($_POST[$fileFieldName]['error']==0) or
				header("Location: ".SITE_URL.$errUrl.
					$php_errors[$_FILES[$fileFieldName]['error']]);

			//判断是否是上传的文件
			@is_uploaded_file($_FILES[$fileFieldName]['tmp_name']) or 
				header("Location: ".SITE_URL.$errUrl."上传错误文件".$_FILES[$fileFieldName]['tmp_name']);

			//判断文件类型
			if(!in_array(strtolower(substr(strrchr($_FILES[$fileFieldName]['name'], '.'), 1)),$fileExt)){   
			    $text=implode(",",$fileExt);
			    header("Location: ".SITE_URL.$errUrl."您只能上传以下类型文件: ".$text);
			}    
			 
			//文件重命名
			$now = time();
			while(file_exists($fileName=$upload_dir.$now.'-'.$_FILES[$fileFieldName]['name'])) {
				$now++;
			}

			//储存文件
			if (move_uploaded_file($_FILES[$fileFieldName]['tmp_name'],$fileName)){
			
				date_default_timezone_set('Asia/Shanghai');
				$inputFileName = $fileName;
				$objPHPExcel = PHPExcel_IOFactory::load($inputFileName) or
					header("Location: ".SITE_URL.$errUrl."文件加载失败");
				//从文件中读取数据
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$sheetData = array_slice($sheetData, 1);

				//print_r($sheetData);exit;

				//将数据保存到数据库中
				foreach ($sheetData as $data) {

					$option = array('table'=>$usersTable,
									'where'=>array("username"=>$data['A']),
								);

					if (!isExist($option, $db)) {
						$salt = $db->salt();
						$passWord = $db->password($salt, $data['A']);
						$memberInfo = array('mid'=>2, 
											'username'=>$data['A'],
											'realname'=>$data['B'],
											'salt'=>$salt,
											'password'=>$passWord,
											);

						$result = $db->insert($usersTable, $memberInfo);
						if(!$result){
							header("Location: ".SITE_URL.$errUrl."导入数据失败");
						}
					}
				}
				header("Location: ".SITE_URL."successpage.php?msg=导入数据成功");
			}else{
				header("Location: ".SITE_URL.$errUrl."导入数据失败");
			}

		}

		$assignVar = array("cssArr"=>$cssArr, 
						   "jsArr"=>$jsArr, 
						   "userInfo"=>$userInfo
						   );

		$smarty->assign($assignVar);

		$smarty->display(ADMIN_TEM_DIR."upload_data.html");
?>